package cn.xfyun.example.util;

import cn.xfyun.example.config.AppConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class InterviewService {

    private final JdbcTemplate jdbcTemplate;
    private final AppConfig appConfig;

    @Autowired
    public InterviewService(JdbcTemplate jdbcTemplate, AppConfig appConfig) {
        this.jdbcTemplate = jdbcTemplate;
        this.appConfig = appConfig;
    }

    /**
     * 更新 interviews 表中指定 interviewId 的 summary 和 status 字段
     * @param interviewId 面试记录 ID
     * @param summaryMap JSON 格式的摘要信息
     */
    @Transactional
    public void updateSummaryAndStatus(String interviewId, ConcurrentHashMap<String, JSONObject> summaryMap) {
        String sqlSummary = "UPDATE interviews SET summary = ? WHERE interview_id = ?";
        String sqlStatus = "UPDATE interviews SET status = ? WHERE interview_id = ?";
        String sqlEndTime = "UPDATE interviews SET end_time = NOW() WHERE interview_id = ?"; // 新增 SQL 语句


        // 提取第一个 value 值
        JSONObject summaryObj = summaryMap.values().iterator().next();
        if (summaryObj == null) {
            System.err.println("输入 map 中没有有效数据。");
            return;
        }

        String summaryStr = summaryObj.toJSONString();
        System.out.println("Interview summary: " + summaryStr);

        try {
            // 1. 更新 summary
            jdbcTemplate.update(sqlSummary, summaryStr, interviewId);
            System.out.println("Interview summary updated for ID: " + interviewId);

            // 2. 更新 status 为 "完成"
            jdbcTemplate.update(sqlStatus, "已完成", interviewId);
            System.out.println("Interview status updated to '完成' for ID: " + interviewId);

            // 3. 更新 end_time 为当前时间
            jdbcTemplate.update(sqlEndTime, interviewId);
            System.out.println("Interview end_time updated to current time for ID: " + interviewId);

        } catch (Exception e) {
            System.err.println("Failed to update interview data: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
